package com.guodi.map.controller;

import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.DateUtil;
import com.guodi.common.utils.ExcelUtil;
import com.guodi.common.utils.ReadFileUtil;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.tool.api.R;
import com.guodi.map.entity.MapParam;
import com.guodi.map.mapper.MapParamMapper;
import com.guodi.map.service.IMapParamService;
import com.guodi.map.vo.ApiMapParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @描述：地图参数列表控制类
 * @作者: 代鹏刚
 * @日期: 2019-12-12
 */
@Validated
@RestController
@RequestMapping("/MapParam")
@Api(value = "API - MapParamController", tags = "地图参数列表")
public class MapParamController extends BaseController {

    @Autowired
    public IMapParamService mapParamService;

    @Resource
    private MapParamMapper mapParamMapper;

    /**
    * @描述: 根据参数方案与行政区划代码获取参数
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2019-12-12
    **/
    @PostMapping("/listBySchemeAndOrg")
    @ApiOperation(value = " 根据参数方案与行政区划代码获取参数")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "schemeId", value = "参数方案ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码", dataType = "string", paramType = "query")
    })
    public R listBySchemeAndOrg(String schemeId, String divisionCode){
        List<MapParam> mapParams = mapParamService.listBySchemeAndOrg(schemeId,divisionCode);
        return R.data(mapParams);
    }

    /**
     * @描述: 根据主键查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-12
     **/
    @PostMapping("/findById")
    @ApiOperation(value = "根据主键查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public R findById(String id) {
        if(StringUtils.isBlank(id)){
            return R.fail(StatusCode.ERROR_CODE_40005,"id不能为空");
        }
        MapParam mapParam = mapParamService.getById(id);
        return R.data(mapParam);
    }

    /**
     * @描述: 新增
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-12
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    public R save(@Valid ApiMapParam apiMapParam){
        MapParam mapParam = new MapParam();
        BeanUtils.copyProperties(apiMapParam,mapParam);
        if(!(prepareData(mapParam, true))){
            return R.fail(StatusCode.ERROR_CODE_40005,"该行政区划地图参数已经存在，请检查！");
        }
        if(mapParam.getMapZoom()!=null&&mapParam.getMapZoom().equals(-1L)){
            mapParam.setMapZoom(null);
        }
        mapParam.setId(UuidUtil.get32UUID());
        mapParamService.save(mapParam);

        return R.data(mapParam);
    }

    /**
     * @描述: 修改
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-12
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public R update(MapParam mapParam) {
        if(!(prepareData(mapParam, false))){
            return R.fail(StatusCode.ERROR_CODE_40005,"该机构地图参数已经存在，请检查！");
        }
        mapParamService.updateById(mapParam);
        if(mapParam.getMapZoom()!=null&&mapParam.getMapZoom().equals(-1L)){
            mapParamMapper.updateMapZoom(mapParam);
        }
        return R.data(mapParam);
    }

    /**
     * @描述: 根据主键删除
     * @入参: id
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-12
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除", required = true, allowMultiple=true,dataType = "string", paramType = "query")
    })
    public R delete(String[] ids){
        if(ids.length > 0 && ids != null){
            for (String id:ids
                 ) {
                mapParamService.removeById(id);
            }
        }
        return R.data(null);
    }

    /**
    * @描述: 导出Excel
    * @作者: 代鹏刚
    * @日期: 2019/12/12 19:40
    **/
    @PostMapping("/exportExcel")
    @ApiOperation(value = "导出Excel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        //查询地图参数数据
        List<MapParam> mapParamList = mapParamService.list();
        ExcelUtil.exportExcel(mapParamList, "地图参数设置", "地图参数表", MapParam.class,
                "MapParam"+ DateUtil.getDay(),response);
    }

    /**
    * @描述: 读取上传cdi文件
    * @作者: 代鹏刚
    * @日期: 2019/12/17 16:56
    **/
    @PostMapping("/loadMapExtext")
    @ApiOperation(value = "读取上传cdi文件")
    public R loadMapExtext(MultipartHttpServletRequest request) {
        R ajaxResult = R.data(true);
        MultipartFile multipartFile = request.getFile("file");
        String resolution = ReadFileUtil.loadMapextent(multipartFile, 2048);
        resolution = resolution.replaceAll("\r?\n", "").replace("\"", "") ;
        ajaxResult.setData(resolution);
        return ajaxResult;
    }

    /**
    * @描述: 读取上传xml文件
    * @作者: 代鹏刚
    * @日期: 2019/12/17 17:01
    **/
    @PostMapping("/loadResolution")
    @ApiOperation(value = "读取上传xml文件")
    public R loadResolution(MultipartHttpServletRequest request) {
        R ajaxResult = R.data(true);
        MultipartFile multipartFile = request.getFile("file");
        String resolution = ReadFileUtil.loadResScl(multipartFile, 2048);
        resolution = resolution.replaceAll("\r?\n", "").replace("\"", "") ;
        ajaxResult.setData(resolution);
        return ajaxResult;
    }

    private boolean prepareData(MapParam mapParam, boolean isSave) {
        Map map = new HashMap();
        map.put("division_code", mapParam.getDivisionCode());
        map.put("scheme_id", mapParam.getSchemeId());
        List<MapParam> mapParams = (List<MapParam>)mapParamService.listByMap(map);
        if(isSave){
            if(mapParams.size() > 0){
                return false;
            }
            mapParam.setCreator(getUser().getUserId().toString());
            mapParam.setCreateTime(new Date());
            //防止误修改
            mapParam.setModifier(null);
            mapParam.setModifyTime(null);
            return true;
        }else{
            if(mapParams.size() > 0 && !mapParams.get(0).getId().equals(mapParam.getId())){
                return false;
            }
            mapParam.setModifier(getUser().getUserId().toString());
            mapParam.setModifyTime(new Date());
            //防止误修改
            mapParam.setCreator(null);
            mapParam.setCreateTime(null);
            return true;
        }
    }
}
